import React from 'react';
import { connect } from 'dva';
import { Select, DatePicker, Button, Table, Pagination, message } from 'antd';
import { VtxGrid } from 'vtx-ui';
import { NAME_SPACE, stateList, SearchParams } from '../../../components/CollectionAmountMonitor/config'
import styles from './collectionAmountMonitor.less'
import _ from 'lodash'
import moment from 'moment'
import Timer from '../../../components/CollectionAmountMonitor/Timer'
import Details from '../../../components/CollectionAmountMonitor/Details'
import PicModel from '../../../components/CollectionAmountMonitor/Model'

const Option = Select.Option

const Index = ({dispatch, collectionAmountMonitor}) => {

  const {
    loading,
    pageNo,
    pageSize,
    total,
    searchParams,
    oldSearchParams,
    dataList,
    // 详情可见
    detailsModelVisable,
    details,
    detailsLoading,
    detailsPageNo,
    detailsPageSize,
    detailsTotal,
    detailsSearchParams,
    //  是否刷新
    refresh,
    // 图片可见
    picVisable,
    // 可选
    choice,
    // 人员列表
    userList,
    // 车辆列表
    carList,
    // 详情id
    modifyId,
    // 人员名字
    userName,
    // 车牌号
    carNum,
    // 图片列表
    imgList,
  } = collectionAmountMonitor;

  const gridProps = {
    titles: ['日期选取', '车牌号', '作业人员', '任务状态'],
    gridweight: [1,1,1,1],
    // 点击确定
    confirm: () => {
      dispatch({
        type: `${NAME_SPACE}/getList`,
        payload: {
          type: 'search'
        }
      })
    },
    // 重置
    clear: () => {
      dispatch({
        type:`${NAME_SPACE}/updateState`,
        payload:{
            searchParams: {
                ...SearchParams
            },
            pageNo: 1,
            pageSize: 20,
        }
      });
      dispatch({
          type:`${NAME_SPACE}/getList`,
          payload:{type:"search"}
      });
    },
  };

  // 显示详情
  const showDetail = (id, userName, carNum) => {
    dispatch({
      type: `${NAME_SPACE}/updateSubState`,
      payload: {
        sub: 'detailsSearchParams',
        data: {
          userCarId: id,
          // day: oldSearchParams.day
        }
      }
    })
    dispatch({
      type: `${NAME_SPACE}/getDetailsList`,
      payload: { type: 'search'}
    })
    dispatch({
      type: `${NAME_SPACE}/updateState`,
      payload: {
        detailsModelVisable: true,
        userName: userName,
        carNum: carNum
      }
    });
    
  }

  const selectDateChange = (name, value) => {
    // console.log(value)
    dispatch({
      type: `${NAME_SPACE}/updateSubState`,
      payload: {
        sub: 'searchParams',
        data: {
          [name]: value
        }
      }
    })
    dispatch({
      type: `${NAME_SPACE}/updateSubState`,
      payload: {
        sub: 'detailsSearchParams',
        data: {
          day: value,
        }
      }
    })
    if(value != moment().format('YYYY-MM-DD')){
      dispatch({
        type: `${NAME_SPACE}/updateState`,
        payload: {
          refresh: false
        }
      })
    }else{
      dispatch({
        type: `${NAME_SPACE}/updateState`,
        payload: {
          refresh: true
        }
      })
    }
  };
  const selectNumChange = (name, value) => {
    if(value.length>4){
      // message.warning('最多选4个')
      dispatch({
        type: `${NAME_SPACE}/updateSubState`,
        payload: {
          sub: 'searchParams',
          data: {
            [name]: value.slice(0,4).join(',')
          }
        }
      })
    }else{
      dispatch({
        type: `${NAME_SPACE}/updateSubState`,
        payload: {
          sub: 'searchParams',
          data: {
            [name]: value.join(',')
          }
        }
      })
    }
  }

  const selectChange = (name, value) => {
    dispatch({
      type: `${NAME_SPACE}/updateSubState`,
      payload: {
        sub: 'searchParams',
        data: {
          [name]: value
        }
      }
    })
    dispatch({
      type: `${NAME_SPACE}/updateSubState`,
      payload: {
        sub: 'detailsSearchParams',
        data: {
          [name]: value
        }
      }
    })
  }

  const indexOf = (value) => {
    if(value.length > 0){
      if(value.indexOf(',') == -1){
        return [value]
      }else{
        return value.split(',')
      }
    }else{
      return []
    }
  }

  const detailsProps = {
    dispatch,
    detailsLoading,
    detailsPageNo,
    detailsPageSize,
    detailsTotal,
    detailsSearchParams,
    userName,
    carNum,
    details,
  }

  const modelProps = {
    dispatch,
    imgList,
    picVisable,
  }

  const tableProps = {
    autoFit: true,
    hideColumn: true,
    indexColumn: true,
    showHeader: true,
    scroll:{
      y:`${document.documentElement.clientHeight - 100 - 120}px`,
    },
    startIndex: (pageNo) * pageSize + 1,
    dataSource: dataList,
    loading: loading,
    pagination: false,
    columns: [
      {
        title: '序号', 
        key: '0',
        dataIndex: '0',
        ellipsis: true,
        render: (text, record, index) => {return `${index+1}`}
      },{
        title: '车牌号', 
        key: 'carNum',
        dataIndex: 'carNum',
        ellipsis: true,
      },{
        title: '作业人员', 
        key: 'userName',
        dataIndex: 'userName',
        ellipsis: true,
      },{
        title: '医疗机构收集数量(个)', 
        key: 'auditType',
        dataIndex: 'auditType',
        ellipsis: true,
        sorter: (a, b) => a.auditType - b.auditType
      },{
        title: '医废收集桶数(个)', 
        key: 'collectorBucketNum',
        dataIndex: 'collectorBucketNum',
        ellipsis: true,
        sorter: (a, b) => a.collectorBucketNum - b.collectorBucketNum
      },{
        title: '医废收集重量(KG)', 
        key: 'collectorWeight',
        dataIndex: 'collectorWeight',
        ellipsis: true,
        sorter: (a, b) => a.collectorWeight - b.collectorWeight
      },
      // {
      //   title: '任务状态', 
      //   key: '6',
      //   dataIndex: '6',
      //   ellipsis: true,
      // },
      {
        title: '操作', 
        key: '7',
        dataIndex: '7',
        ellipsis: true,
        render: (text, record, index) => {
          return(
            <div className={styles.toDo}>
              <a onClick={() => {showDetail(record.userCarId, record.userName, record.carNum )}}>详情</a>
            </div>
          )
        }
      },
    ],
    rowKey: (record, index) => {
      
    },
    // rowSelection: {
    //   type: 'checkbox',
    //   selectedRowKeys: selectedRowKeys || [],
    //   onChange: (selectedRowKeys, selectedRows) => {
    //     let ids = selectedRows.map((item) => {
    //         return item.id;
    //     });
    //     dispatch({
    //       type: `${NAME_SPACE}/updateState`,
    //       payload: {
    //         selectedRowKeys: ids
    //       }
    //     })
    //     // updateState({ selectedRowKeys: ids})
    //   },
    // },
  };
  const pagProps = {
    current: pageNo ,
    defaultCurrent: 1,
    total: total,
    pageSize: pageSize,
    showQuickJumper: true,
    showSizeChanger: true,
    onChange: (page) => {
      dispatch({
        type: `${NAME_SPACE}/updateState`,
        payload: {
          pageNo: page 
        }
      });
      dispatch({
        type: `${NAME_SPACE}/getList`,
        payload: {
          type: 'page'
        }
      })
    },
    showTotal: (total) => {
        return `合计${total}条数据`
    },
    onShowSizeChange: (current, pageSize) => {
      dispatch({
        type: `${NAME_SPACE}/updateState`,
        payload: {
          pageNo: 1,
          pageSize: pageSize,
        }
      })
      dispatch({
        type: `${NAME_SPACE}/getList`,
        payload: {
          type: 'page'
        }
      })
    },
  };

  const timerProps = {
    dispatch
  }

  return (
    <div className={styles.normal}>
      {/* 弹窗 */}
      <PicModel {...modelProps}/>
      {
        !detailsModelVisable?
          <div>
            <div className={styles.header}>
              <VtxGrid {...gridProps}>
                <DatePicker
                  style={{width: '100%'}}
                  value={moment(_.get(searchParams, 'day', ''))}
                  onChange={(data, dateString) => {selectDateChange('day' ,dateString)}}
                  // onChange={(data, dateString) => {console.log(data, dateString)}}
                  format={'YYYY-MM-DD'}
                />
                <Select
                  style={{width: '100%'}}
                  value={indexOf(searchParams.carIds)}
                  onChange={(value) => {selectNumChange('carIds',value)}}
                  allowClear={true}
                  mode="multiple"
                  optionFilterProp='children'
                  maxTagCount={1}
                >
                  {
                    Array.isArray(carList)?
                      carList.map((item, index) => {
                        return (<Option value={item.carId}>{item.carNum}</Option>)
                      })
                    :''
                  }
                </Select>
                <Select
                  style={{width: '100%'}}
                  value={indexOf(searchParams.userIds)}
                  onChange={(value) => {selectNumChange('userIds',value)}}
                  allowClear={true}
                  mode="multiple"
                  optionFilterProp='children'
                  maxTagCount={2}
                >
                  {
                    Array.isArray(userList)?
                      userList.map((item, index) => {
                        return (<Option value={item.userId}>{item.userName}</Option>)
                      })
                    :''
                  }
                </Select>
                <Select
                  style={{width: '100%'}}
                  value={searchParams.statusStr}
                  onChange={(value) => {selectChange('statusStr', value)}}
                  allowClear={true}
                >
                  {
                    Array.isArray(stateList)?
                      stateList.map((item, index) => {
                        return (<Option value={item.id}>{item.name}</Option>)
                      })
                    :''
                  }
                </Select>
              </VtxGrid>
            </div>
            {
              refresh?
                <Timer {...timerProps}/>
              :
                ''
            }
            <div className={styles.table} style={{ height: document.documentElement.clientHeight-100 }}>
              <div className={styles.tableContent}>
                <Table {...tableProps}/> 
              </div>  
              <div className={styles.pagination}>
                <span className={styles.pagContent}> <Pagination {...pagProps}/> </span>  
              </div>  
            </div> 
          </div> 
        :
          <Details {...detailsProps}/>
      }
    </div>
  )
}
export default connect(state=>state)(Index)